package com.github.cakin.shiro.chapter17.service;

import com.github.cakin.shiro.chapter17.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import static com.github.cakin.shiro.chapter17.Constants.NUM2;

/**
 * @className: PasswordHelper
 * @description: 密码工具类
 * @date: 2020/5/19
 * @author: cakin
 */
@Service
public class PasswordHelper {
    /**
     * 随机数生成器
     */
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    /**
     * 哈希算法
     */
    @Value("${password.algorithmName}")
    private String algorithmName = "md5";
    /**
     * 迭代次数
     */
    @Value("${password.hashIterations}")
    private int hashIterations = NUM2;

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setHashIterations(int hashIterations) {
        this.hashIterations = hashIterations;
    }

    public void encryptPassword(User user) {

        user.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
}
